<?php


class Cms_Model_Template extends WSB_Db_Row
{

	public function init()
	{
		$this->_formConfigPath = WSB_MODULES_PATH . 'cms/forms/template.config';
	}

	/**
	 * @var string
	 */
	public function getTitle()
	{
	   return $this->name;
	}

	/**
	 * Gib alle gueltigen Platzhalter fuer das aktuelle Templateobjekt zurueck.
	 *
	 * @return Cms_Model_Placeholders
	 */
	public function getPlaceholders()
	{
		preg_match_all('#{{([0-9]+)}}#ie', $this->getHtmlFromNestedTemplates(), $matches);
		//preg_match_all('#{{([0-9]+)}}#ie', $this->html, $matches);
		if(array_key_exists(1, $matches) && (count($matches[1]) > 0)) {
			$table = new Cms_Model_DbTable_Placeholder();
			$where = $table->getAdapter()->quoteInto('id IN (?)', $matches[1]);
			$rowset = $table->fetchAll($where);
			$rowset->sortByIds($matches[1]);
			return $rowset;
		}
		return new Cms_Model_Placeholders(array());
	}

	/**
	 * @param Zend_View_Interface $view
	 * @return string
	 */
	public function getHtmlFromNestedTemplates(Zend_View_Interface $view = null)
	{
		$table = new Cms_Model_DbTable_Template();
		$collection = $table->fetchAll('deleted=0 AND hidden=0');
		return $collection->renderHtml($this->id, $view);
	}

	/**
	 * Gib die Stylesheets fuer das aktuelle Template zurueck.
	 *
	 * @return array Ein Array von stdClass-Objekten mit den Members rel, href und media.
	 */
	public function getStylesheets()
	{
		$stylesheets = array();
		foreach(WSB_Div::explode(chr(13), $this->stylesheets) AS $stylesheet) {
			$parts = WSB_Div::explode(';', $stylesheet);
			// 0 => href
			// 1 => media
			$parts[1] = empty($parts[1]) ? 'screen' : $parts[1];
			$oStylesheet = new stdClass();
			$oStylesheet->rel	= 'stylesheet';
			$oStylesheet->href	= $parts[0];
			$oStylesheet->media	= $parts[1];
			$stylesheets[] = $oStylesheet;
		}
		return $stylesheets;
	}

}